/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年10月27日
 */
package com.massyframework.beanskin.runtime.framework.protocol;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLStreamHandlerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * URLStreamHandlerFactory 工具类
 * @author huangkh
 *
 */
public class URLStreamHandlerFactoryUtils {
	
	public static void initURLStreamHandlerFactory() {
		try {
			//通过反射获取 URL的factory字段
			Class<?> clazz = URL.class;
			Field factoryField = clazz.getDeclaredField("factory");
			factoryField.setAccessible(true);
			
			Field lockField = clazz.getDeclaredField("streamHandlerLock");
			lockField.setAccessible(true);
			Object lockObj = lockField.get(null);
			if (lockObj != null) {
				synchronized(lockObj) {
					URLStreamHandlerFactory factory = (URLStreamHandlerFactory)factoryField.get(null);	
					factoryField.set(null, null);
					URL.setURLStreamHandlerFactory(new ModuleURLStreamHandlerFactory(factory));
				}
			}else {
				URLStreamHandlerFactory factory = (URLStreamHandlerFactory)factoryField.get(null);	
				URL.setURLStreamHandlerFactory(new ModuleURLStreamHandlerFactory(factory));
			}
		
		}catch(Exception e) {
			Logger logger = LoggerFactory.getLogger(URLStreamHandlerFactoryUtils.class);
			if (logger.isErrorEnabled()) {
				logger.error("set URLStreamHandlerFactory failed.", e);
			}
		}
	}
}
